
from hero import hero
from pymysql import Connection
class Operation:
    def __init__(self):
        self.conn = Connection(
            user="root",
            password="123456",
            database="mydb1",
            port=3306,
            charset="utf8"
        )
        self.curors = self.conn.cursor()

    def insert(self,hero):
        sql = f"INSERT INTO hero(h_name,age,gender,address) VALUES ('{hero.name}',{hero.age},'{hero.gender}','{hero.address}')"
        self.curors.execute(sql)
        self.conn.commit()
        print("数据添加成功")

    def update(self,hero):
        sql = f"UPDATE hero SET h_name=%(name)s,age=%(age)s,gender=%(gender)s,address=%(address)s WHERE id=%(id)s"
        self.curors.execute(sql,hero.__dict__)
        self.conn.commit()
        print("修改成功")

    def delete(self,id):
        sql = f"DELETE FROM hero WHERE id={id}"
        self.curors.execute(sql)
        self.conn.commit()
        print("删除成功")

    def selectAll(self):
        sql = "SELECT * FROM hero"
        self.curors.execute(sql)
        qure = self.curors.fetchall()
        for item in qure:
            print(item)

    def selectById(self,id):
        sql = f"SELECT * FROM hero WHERE id={id}"
        self.curors.execute(sql)
        one = self.curors.fetchone()
        print(one)

    def my_close(self):
        if self.curors:
            self.curors.close()
        if self.conn:
            self.conn.close()

if __name__== '__main__':
    o=Operation()
    # hero = hero(null,"廉颇",18,"男","王者峡谷")
    # o.insert(hero)

    # hero =hero(1,"李白",20,"男","王者峡谷")
    # o.update(hero)

    # o.delete(3)

    # o.selectAll()

    o.selectById(2)
    o.my_close()